﻿using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;

namespace ImageHandler
{
    public partial class Form1 : Form
    {

        protected string GetImageFromPath = "";
        protected string SaveImageToPath = "";

        public Form1()
        {

            InitializeComponent();

            ImageSizes is1 = new ImageSizes("Original Size", 0, 0);
            ImageSizes is2 = new ImageSizes("1280*1024", 1280, 1024);
            ImageSizes is3 = new ImageSizes("1024*768", 1024, 768);
            ImageSizes is4 = new ImageSizes("800*600", 800, 600);
            ImageSizes is5 = new ImageSizes("640*480", 640, 480);

            ddPictureSize.Items.Clear();

            ddPictureSize.Items.Add(is1);
            ddPictureSize.Items.Add(is2);
            ddPictureSize.Items.Add(is3);
            ddPictureSize.Items.Add(is4);
            ddPictureSize.Items.Add(is5);

            ddPictureSize.DisplayMember = "Description";
            ddPictureSize.SelectedIndex = 0;
            txtImageText.Text = Properties.Settings.Default.DefaultImageText;

#if DEBUG
            FileInfo f1 = new FileInfo(@"D:\Temp\IMG_2190.JPG");
            FileInfo f2 = new FileInfo(@"D:\Temp\IMG_2203.JPG");

            ListViewItem li1 = new ListViewItem();
            li1.Name = f1.Name;
            li1.Tag = f1.FullName;
            li1.Text = f1.Name;

            ListViewItem li2 = new ListViewItem();
            li2.Name = f2.Name;
            li2.Tag = f2.FullName;
            li2.Text = f2.Name;

            FileList.Items.Add(li1);
            FileList.Items.Add(li2);
            ddPictureSize.SelectedIndex = 4;
#endif

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void AddFileToListbox(String file)
        {
            FileInfo fi = new FileInfo(file);

            if (fi.Extension.ToLower() != ".jpg" && fi.Extension.ToLower() != ".jpeg" && fi.Extension.ToLower() != ".gif")
            {
                return;
            }

            ListViewItem li = new ListViewItem();
            li.Name = fi.Name;
            li.Tag = fi.FullName;
            li.Text = fi.Name;

            foreach (ListViewItem item in FileList.Items)
            {
                string listItemFile = item.Tag.ToString();
                if (listItemFile == fi.FullName)
                    return;
            }

            FileList.Items.Add(li);
        }
        private void btnAddPictures_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog fd = new OpenFileDialog())
            {
                fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                fd.Multiselect = true;
                fd.RestoreDirectory = true;
                fd.Filter = "Image files (jpeg, gif, bmp, png)|*.jpg;*.gif;*.bmp;*.jpeg;*.png";
                if (!String.IsNullOrEmpty(Properties.Settings.Default.GetImageFromPath))
                    fd.InitialDirectory = Properties.Settings.Default.GetImageFromPath;
                if (fd.ShowDialog() != DialogResult.Cancel)
                {
                    DirectoryInfo di = new DirectoryInfo(fd.FileName);
                    Properties.Settings.Default.GetImageFromPath = di.Name;
                    Properties.Settings.Default.Save();
                    foreach (String file in fd.FileNames)
                        AddFileToListbox(file);
                }
            }
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            progressBar1.Maximum = FileList.Items.Count;

            using (FolderBrowserDialog folder = new FolderBrowserDialog())
            {
                folder.ShowNewFolderButton = true;
                if (!String.IsNullOrEmpty(Properties.Settings.Default.SaveImageToPath))
                    folder.SelectedPath = Properties.Settings.Default.SaveImageToPath;
                if (folder.ShowDialog() != DialogResult.Cancel)
                {
                    Properties.Settings.Default.SaveImageToPath = folder.SelectedPath;
                    Properties.Settings.Default.Save();
                    progressBar1.Maximum = FileList.Items.Count;
                    foreach (ListViewItem li in FileList.Items)
                    {
                        ImageProcess ip = new ImageProcess
                        {
                            SaveToPath = folder.SelectedPath,
                            OverwriteOriginal = false,
                            listViewItem = li,
                            Width = ((ImageSizes)ddPictureSize.SelectedItem).Width,
                            Height = ((ImageSizes)ddPictureSize.SelectedItem).Height
                        };
                        if (txtImageText.Text != String.Empty)
                            ip.ImageText = txtImageText.Text;
                        ip.ImageProcessed += new ImageProcess.SampleEventHandler(ip_ImageProcessed);
                        //ip.ProcessImage();
                        var t = Task.Factory.StartNew(() => ip.ProcessImage());
                    }
                }
            }
        }

        private void FileList_Click(object sender, EventArgs e)
        {
            //ShowThumbnailImage();
        }

        private void FileList_DoubleClick(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            if (FileList.SelectedItems.Count == 1)
            {
                ASCIIEncoding encoding = new ASCIIEncoding();

                String file = (String)FileList.SelectedItems[0].Tag;
                FileInfo fi = new FileInfo(file);
                if (File.Exists(fi.FullName))
                {
                    Image image = Image.FromFile(fi.FullName);
                    using (image)
                    {
                        foreach (PropertyItem pi in image.PropertyItems)
                        {
                            string s = encoding.GetString(pi.Value);
                            //if (pi.Id == 42016)
                            //listBox1.Items.Add(pi.Id + " : " + s);

                            if (pi.Type == 2)
                                listBox1.Items.Add(String.Format("{0} : {1}", pi.Id, s));
                        }
                    }
                }
            }
        }

        private void FileList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                foreach (ListViewItem li in FileList.SelectedItems)
                {
                    FileList.Items.Remove(li);
                }
            }
        }

        private void FileList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //ShowThumbnailImage();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.WindowXPos != 0 && Properties.Settings.Default.WindowYPos != 0)
            {
                if (SystemInformation.VirtualScreen.Width > Properties.Settings.Default.WindowXPos)
                    this.Left = Properties.Settings.Default.WindowXPos;
                if (SystemInformation.VirtualScreen.Height > Properties.Settings.Default.WindowYPos)
                    this.Top = Properties.Settings.Default.WindowYPos;
            }
            if (Properties.Settings.Default.WindowWidth != 0 && Properties.Settings.Default.WindowHeight != 0)
            {
                if (SystemInformation.VirtualScreen.Width > this.Left + Properties.Settings.Default.WindowXPos)
                    this.Width = Properties.Settings.Default.WindowWidth;
                else
                    this.Width = SystemInformation.VirtualScreen.Width - Properties.Settings.Default.WindowXPos;

                if (SystemInformation.VirtualScreen.Height > this.Top + Properties.Settings.Default.WindowYPos)
                    this.Height = Properties.Settings.Default.WindowHeight;
                else
                    this.Height = SystemInformation.VirtualScreen.Height - Properties.Settings.Default.WindowYPos;

            }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.WindowXPos = this.Left;
            Properties.Settings.Default.WindowYPos = this.Top;
            Properties.Settings.Default.WindowWidth = this.Width;
            Properties.Settings.Default.WindowHeight = this.Height;
            Properties.Settings.Default.DefaultImageText = txtImageText.Text;
            Properties.Settings.Default.Save();
        }

        void ip_ImageProcessed(object sender)
        {
            //this.progressBar1.Value += 1;
            //this.listBox1.Items.Add(((ImageHandler.ImageProcess)sender).FileName + " processed");
            //throw new NotImplementedException();
        }

        private void FileList_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else
                e.Effect = DragDropEffects.None;
        }

        private void FileList_DragDrop(object sender, DragEventArgs e)
        {
            // Extract the data from the DataObject-Container into a string list
            string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);

            // Do something with the data...

            // For example add all files into a simple label control:
            foreach (string file in FileList)
            {
                AddFileToListbox(file);
            }
        }

    }
}